package com.af.community.smart.business

import android.content.Intent
import android.os.Bundle
import com.af.community.smart.base.*
import com.af.community.smart.model.PeopleData
import com.af.community.smart.utils.bindLifeCycle
import com.af.community.smart.utils.subscribeByFinally
import com.af.community.smart.utils.textString
import com.af.community.smart.utils.toFormat
import com.af.community.smart.viewmodel.PatrolViewModel
import com.baidu.ocr.sdk.OCR
import com.baidu.ocr.sdk.model.IDCardParams
import com.baidu.ocr.ui.camera.CameraActivity
import com.baidu.ocr.ui.util.recognizeIDCard
import kotlinx.android.synthetic.main.activity_patrol_people_scan.*
import org.jetbrains.anko.longToast
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import org.koin.androidx.viewmodel.ext.android.getViewModel
import java.io.File

class PatrolPeopleScanActivity : BaseActivity() {

    private val REQUEST_CODE_CAMERA = 155
    private lateinit var mFilePath: String
    private var mData: PeopleData? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_patrol_people_scan)
        initTitle(title = "详情", name = "录入人口库")

        startToScan()
    }

    override fun getViewModel() = getViewModel<PatrolViewModel>()

    override fun initTitle(title: String, name: String) {
        super.initTitle(title, name)
        tvRight?.gone()
        tvRight?.oneClick {
            if (patrol_id.text.isEmpty()) startToScan()
            else {
                startActivity<PatrolPeopleSelectActivity>(
                    "action" to "add",
                    "data" to mData
                )
            }
        }
        bt_add.oneClick {
            if (patrol_id.text.isEmpty()) startToScan()
            else startActivity<PatrolAddActivity>("people" to mData)
        }
    }

    private fun startToScan() {
        val fileName = "pic_${System.currentTimeMillis()}.jpg"
        mFilePath = File(cacheDir, fileName).absolutePath

        startActivityForResult<CameraActivity>(
            REQUEST_CODE_CAMERA,
            CameraActivity.KEY_OUTPUT_FILE_PATH to mFilePath,
            CameraActivity.KEY_CONTENT_TYPE to CameraActivity.CONTENT_TYPE_ID_CARD_FRONT,
            CameraActivity.KEY_NATIVE_TOKEN to OCR.getInstance(baseContext).license
        )
    }

    private fun recIDCard(cardSide: String) {
        showLoading()
        recognizeIDCard(
            IDCardParams().apply {
                // 设置图片路径
                imageFile = File(mFilePath)
                // 设置身份证正反面
                idCardSide = cardSide
                // 设置方向检测
                isDetectDirection = true
                // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
                imageQuality = 20
            }
        ) {
            onResult {
                patrol_img.visible()
                patrol_img.loadImageNoTransform(mFilePath, R.mipmap.default_logo2)

                val nation = it.ethnic?.toString().orEmpty()
                val birth = (it.birthday?.toString().orEmpty()).toFormat("yyyyMMdd")

                patrol_name.text = it.name.toString()
                patrol_sex.text = it.gender?.toString().orEmpty()
                patrol_nation.text = if (nation.isEmpty()) nation else "${nation}族"
                patrol_address.text = it.address?.toString().orEmpty()
                patrol_birth.text = birth
                patrol_id.text = it.idNumber.toString()
            }
            onFinally {
                dismissLoading()
                if (patrol_id.text.isEmpty()) {
                    toast("未识别到身份证信息！")
                } else {
                    getViewModel().getPeopleData(
                        getString("userId"),
                        patrol_id.textString()
                    )
                        .bindLifeCycle(getLifecycleOwner())
                        .subscribeByFinally(
                            event = getViewModel(),
                            onSuccess = {
                                if (it.account.isNullOrEmpty()) {
                                    longToast("该用户信息暂未录入人口库！")
                                    tvRight?.visible()
                                    patrol_bottom.gone()
                                    it.userName = patrol_name.textString()
                                    it.sex = when (patrol_sex.textString()) {
                                        "男" -> "1"
                                        "女" -> "0"
                                        else -> ""
                                    }
                                    it.national = patrol_nation.textString()
                                    it.birthday = patrol_birth.textString()
                                    it.account = patrol_id.textString()
                                } else {
                                    tvRight?.gone()
                                    patrol_bottom.visible()
                                }
                                mData = it
                            }
                        )
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK
            && requestCode == REQUEST_CODE_CAMERA
        ) {
            if (data != null) {
                when (data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE)) {
                    CameraActivity.CONTENT_TYPE_ID_CARD_FRONT -> recIDCard(IDCardParams.ID_CARD_SIDE_FRONT)
                    CameraActivity.CONTENT_TYPE_ID_CARD_BACK -> recIDCard(IDCardParams.ID_CARD_SIDE_BACK)
                }
            }
        }
    }

}
